<template>
  <section v-loading.fullscreen.lock="loading">
    <el-card class="margin-top">
      <div slot="header" class="clearfix relative small-header ">
        <el-row class="flex">
          <el-col :sm="24" :md="8" :lg="8" :xl="8">
            <span class="title-icon margin-right">操作指令信息</span>

            <!-- <div> -->
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-download"
              @click="downOperationInstructionData"
            >
              导出操作指令信息
            </el-button>
          </el-col>
          <el-col
            :sm="24"
            :md="16"
            :lg="16"
            :xl="16"
            class="flex text-blue align-center justify-between"
          >
            <div>
              <span class="margin-lr"
                >总产品预报数量：{{ totalAmount[0] }}
              </span>
              <span class="margin-lr">总换标数量 ：{{ totalAmount[1] }} </span>
              <span class="margin-lr">总清点数量：{{ totalAmount[2] }} </span>
              <span class="margin-lr">总检修数量：{{ totalAmount[3] }} </span>
              <span class="margin-lr">总销毁数量：{{ totalAmount[4] }} </span>
            </div>
            <el-button
              v-if="isEdit"
              type="success"
              size="mini"
              @click="changeCargoInfo"
            >
              保存
            </el-button>
          </el-col>
        </el-row>

        <!-- </div> -->
      </div>

      <hot-table
        ref="hotTable"
        :settings="hotSettings"
        :data="OperationInstructionData"
      />

      <div class="text-red margin-top-sm ">
        <span class="margin-right">如需换标，请提供PDF格式标签</span>
      </div>
    </el-card>
  </section>
</template>

<script>
import { HotTable } from "@handsontable/vue";
// import Handsontable from 'handsontable'
import "handsontable/languages/zh-CN";
import globalData from "@/utils/config";
import * as constant from "@/store/yg/common/constant";
import { ajax } from "@/store/yg/common/utils";
import { checkRowsEmpty } from "@/utils";
export default {
  name: "OrderToOrderToOverseasWarehouseShipping",
  components: {
    HotTable
  },
  props: {
    OperationInstructionData: {
      type: Array,
      default: function(params) {
        return [];
      }
    },
    oldOperationInstructionData: {
      type: Array,
      default: function(params) {
        return [];
      }
    },
    actionUrl: {
      type: String,
      default: ""
    },
    waybillId: {
      type: Number,
      default: 1
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    verifyShow: {
      type: Object,
      default: function() {
        return {};
      }
    }
  },
  watch: {
    OperationInstructionData: {
      handler(newValue, oldValue) {
        for (const i of this.OperationInstructionData) {
          if (i.isMixedLoad === 0) {
            i.isMixedLoad = "单独装箱";
          } else if (i.isMixedLoad === 1) {
            i.isMixedLoad = "混装";
          }
        }
        if (newValue.length === 0) {
          this.$emit("update:OperationInstructionData", [{}]);
        }
        const length = newValue.length;
        if (length < 3) {
          this.autoHeight = "250px";
        } else {
          this.autoHeight = "auto";
        }
      }
      // deep: true,
      // immediate: true
    }
  },
  computed: {
    totalAmount() {
      let totalNums = 0;
      let changeNums = 0;
      let checkNums = 0;
      let repairNums = 0;
      let destoryNums = 0;

      for (const i of this.OperationInstructionData) {
        if (i.totalNum) {
          totalNums += parseInt(i.totalNum);
        }
        if (i.changeNum) {
          changeNums += parseInt(i.changeNum);
        }
        if (i.checkNum) {
          checkNums += parseInt(i.checkNum);
        }
        if (i.repairNum) {
          repairNums += parseInt(i.repairNum);
        }
        if (i.destoryNum) {
          destoryNums += parseInt(i.destoryNum);
        }
      }

      return [totalNums, changeNums, checkNums, repairNums, destoryNums];
    },
    hotSettings() {
      return {
        rowHeaders: true, // 行表头
        stretchH: "all", // 所有列宽小于表宽时,填充满整个表 all（所有列填充）/last（最后一列）/none(不填充)
        licenseKey: globalData.licensekey,
        // 定义表结构
        colHeaders: [
          '<i style="color:red;margin-right:3px">*</i>旧FNSKU<br>(old)',
          "退货编号",
          '<i style="color:red;margin-right:3px">*</i>Quantity of Product forecast<br>产品预报个数',
          "NEW FNSKU#<br>新FNSKU",
          "Quantity of relabeling<br>换标数量",
          "Count the quantity<br>清点数量",
          "Quantity of repair<br>检修数量",
          "Quantity of destruction<br>销毁数量",
          "FBA warehouse address code FBA<br>仓库地址代码",
          '<i style="color:red;margin-right:3px">*</i>Single FNSKU or Mixed packed<br>单独装箱或混装',
          "Operational requirements<br>操作要求",
          "Operation description<br>操作说明",
          "操作"
        ],
        width: "100%",
        height: this.autoHeight,

        columns: [
          {
            data: "oldSku", // 指定所指列
            width: 100,
            allowEmpty: false,
            type: "text" // 类型
          },
          {
            data: "returnNo",
            width: 100,
            allowEmpty: false,
            readOnly: true,
            type: "text"
          },
          {
            data: "totalNum",
            width: 100,
            allowEmpty: false,
            type: "text"
          },
          {
            data: "newSku",
            width: 100,
            type: "text"
          },
          {
            data: "changeNum",
            width: 100,
            type: "numeric",
            numericFormat: {
              pattern: "0"
            }
          },
          {
            data: "checkNum",
            width: 100,
            type: "numeric",
            numericFormat: {
              pattern: "0"
            }
          },
          {
            data: "repairNum",
            width: 100,
            type: "numeric",
            numericFormat: {
              pattern: "0"
            }
          },
          {
            data: "destoryNum",
            width: 100,
            type: "numeric",
            numericFormat: {
              pattern: "0"
            }
          },
          {
            data: "fbaCode",
            width: 100,
            type: "numeric",
            numericFormat: {
              pattern: "0"
            }
          },
          {
            data: "isMixedLoad",
            width: 100,
            type: "dropdown",
            source: ["单独装箱", "混装"]
          },
          {
            data: "operatorAsk",
            width: 100,
            type: "numeric",
            numericFormat: {
              pattern: "0"
            }
          },
          {
            data: "operatorIns",
            width: 100,
            type: "numeric",
            numericFormat: {
              pattern: "0"
            }
          },
          {
            readOnly: true,
            // width: 100,
            renderer: this.coverRenderer
          }
        ],
        tableClassName: ["first-class-name", "second-class-name"],
        language: "zh-CN",
        contextMenu: ["row_above", "row_below", "remove_row", "alignment"], // 开启右键菜单
        beforeRemoveRow: (index, amount, physicalRows, source) => {
          if (this.OperationInstructionData.length === 1) {
            this.OperationInstructionData.push({});
          }
        },
        afterCreateRow: (index, amount, source) => {}
      };
    }
  },
  data() {
    return {
      uploadDialog: false,
      loading: false,
      autoHeight: "auto",
      waybillGoodsInfos: [{ isMixedLoad: 1 }, {}, {}, {}, {}]
    };
  },

  methods: {
    closeDialog() {
      this.uploadDialog = false;
    },
    async downOperationInstructionData() {
      const { path, fileName } = await ajax("downLoadInstruction", {
        id: this.waybillId
      });
      if (fileName) {
        window.open(constant.FILE_SERVER + fileName);
        // window.open(constant.FILE_SERVER + fileName);
      }
    },

    changeCargoInfo() {
      for (const i of this.$refs.hotTable.data) {
        if (!i.oldSku || !i.totalNum || !i.isMixedLoad) {
          this.$message.error("请填写必填信息");
          return;
        }
      }
      // TODO 保存操作
      this.saveInfo();
    },
    async saveInfo() {
      // 标记已删除数据
      this.loading = true;
      const arr = [];
      for (const i of this.oldOperationInstructionData) {
        const target = this.OperationInstructionData.find(x => x.id === i.id);
        console.log("target :>> ", target);
        if (!target) {
          i.isDel = true;
          arr.push(i);
        }
      }
      const params = [...this.OperationInstructionData, ...arr];

      // TODO
      for (const i of params) {
        if (!i.waybillId) {
          i.waybillId = this.waybillId;
        }
        if (i.isMixedLoad === "单独装箱") {
          i.isMixedLoad = 0;
        } else if (i.isMixedLoad === "混装") {
          i.isMixedLoad = 1;
        }
      }

      const { code, message } = await ajax("updateOperationInstruct", {
        abroadOperationInstructs: params
      });
      this.loading = false;
      if (code === 200) {
        this.$message({
          type: "success",
          message: "保存成功"
        });
      } else {
        this.$message.error(message);
      }
    },
    coverRenderer(instance, td, row, col, prop, value, cellProperties) {
      td.innerHTML = ``; // 清空单元格子集

      let btnDel = document.createElement("i");

      btnDel.setAttribute(
        "class",
        "el-icon-remove-outline margin-right-sm text-red"
      );
      btnDel.setAttribute("v-loading.fullscreen.lock", "fullscreenLoading");
      btnDel.onclick = params => {
        // console.log("this :>> ", this);
        this.onDel(row);
      };
      // if (
      //   (this.templateType === "receivable" && this.verifyShow.deleteRece) ||
      //   (this.templateType === "payable" && this.verifyShow.deletePay)
      // ) {
      td.appendChild(btnDel); //添加按钮到单元格
      // }

      return td;
    },
    // 删除海外仓库存

    async onDel(row) {
      console.log("row :>> ", row);
      this.loading = true;
      if (this.operationInstructionData[row].id) {
        const data = await ajax("deleteOperationInstruct", {
          id: this.OperationInstructionData[row].id
        });
        if (data.code === 200) {
          this.$message.success("删除成功！");
          this.OperationInstructionData.splice(row, 1);
        } else {
          this.$message.error(data.message || "删除失败！");
        }
      } else {
        this.OperationInstructionData.splice(row, 1);
      }
      this.loading = false;
    }
  }
};
</script>

<style lang="scss" scoped></style>
<style scoped>
/deep/ .el-card__header {
  padding: 8px 20px;
}

.header-save-btn {
  top: 0%;
}
</style>
